package exec;

import java.util.Arrays;

/**
* @description: 统计1的个数
* @author: wangjun
* @create: 2022-04-22
*/
public class Statistication {

    public static void main(String[] args) {
//        Statistication statistication = new Statistication();
//        System.out.println(statistication.statistical(7));
        int[] ints = countBits(5);
        for (int i = 0; i < ints.length; i++) {
            System.out.print(ints[i]+" ");
        }
    }


    /**
     * 给定一个n，判断二进制中1出现的次数
     * @param n 整数n
     * @return int
    */
    public int statistical(int n){
        int count = 0;
        while (n != 0){
            n = n & (n -1);
            count++;
        }
        return count;
    }

    /**
     * 给定一个数组，返回从0到这个数字的每个二进制中1的个数
     * @param num
     * @return int[]
    */
    public static int[] countBits(int num) {
        int[] bits = new int[num+1];
        Arrays.fill(bits, 0);
        for (int i = 1; i <= num; i++) {
            // i & (i-1)将i的最低位置为0，每个i比i-1多1 ，所以最后加1
            bits[i] = bits[i & (i-1)] + 1;
        }
        return bits;
    }
}